import 'dart:io';
import 'package:dio/dio.dart';
import '../net/dio_utils.dart';
import '../net/error_handle.dart';
import '../util/toast_utils.dart';
import 'base_presenter.dart';
import 'mvps.dart';

class BasePagePresenter<V extends IMvpView> extends BasePresenter<V> {
  BasePagePresenter() {
    _cancelToken = CancelToken();
  }

  late CancelToken _cancelToken;

  @override
  void dispose() {
    /// 销毁时，将请求取消
    if (!_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
  }

  /// 返回Future 适用于刷新，加载更多
  Future<dynamic> requestNetwork<T>(
    Method method, {
    required String url,
    bool isShow = false,
        String loadingNotice = "",
    bool isClose = true,
    bool isShowErrorToast = true,
    BASE_URL? urlType,
    NetSuccessCallback<T?>? onSuccess,
    NetErrorCallback? onError,
    dynamic params,

    Map<String, dynamic>? queryParameters,
    CancelToken? cancelToken,
    Options? options,
  }) {
    if (isShow) {
      if(loadingNotice==""){
        view.showProgress();
      }else{
        view.showMsgProgress(loadingNotice);
      }
    }

    return DioUtils.instance.requestNetwork<T>(
      method,
      url,
      urlType: urlType,
      params: params,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken ?? _cancelToken,
      onSuccess: (data) {
        // MyLog.e("============isClose========${data?.toString() ?? "null"}");
        if (isClose) {
          view.closeProgress();
        }
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(int.parse(code), msg, onError,isShowErrorToast);
      },
    );
  }

  void asyncRequestNetwork<T>(
    Method method, {
    required String url,
    bool isShow = true,
    bool isClose = true,
    bool isShowErrorToast = true,
    BASE_URL? urlType,
    NetSuccessCallback<T?>? onSuccess,
    NetErrorCallback? onError,
    dynamic params,
    Map<String, dynamic>? queryParameters,
    CancelToken? cancelToken,
    Options? options,
  }) {
    if (isShow) {
      view.showProgress();
    }
    DioUtils.instance.asyncRequestNetwork<T>(
      method,
      url,
      urlType: urlType,
      params: params,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken ?? _cancelToken,
      onSuccess: (data) {
        if (isClose) {
          view.closeProgress();
        }
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(int.parse(code), msg, onError,isShowErrorToast);
      },
    );
  }

  //请求并返回原样
  void requestNetworkBackCallOriginal(
      Method method, {
        required String url,
        bool isShow = true,
        bool isClose = true,
        bool isShowErrorToast = true,
        BASE_URL? urlType,
        NetSuccessCallbackOrignal? onSuccess,
        NetErrorCallback? onError,
        dynamic params,
        Map<String, dynamic>? queryParameters,
        CancelToken? cancelToken,
        Options? options,
      }) {
    if (isShow) {
      view.showProgress();
    }
    DioUtils.instance.requestNetworkBackCallOriginal(
      method,
      url,
      urlType: urlType,
      params: params,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken ?? _cancelToken,
      onSuccess: (data) {
        if (isClose) {
          view.closeProgress();
        }
        onSuccess?.call(data);
      },
      onError: (code, msg) {
        _onError(int.parse(code), msg, onError,isShowErrorToast);
        view.closeProgress();
      },
    );
  }

  /// 上传图片实现
  Future<String> uploadImg(File image) async {
    String imgPath = '';
    try {
      final String path = image.path;
      final String name = path.substring(path.lastIndexOf('/') + 1);
      final FormData formData = FormData.fromMap(<String, dynamic>{
        'uploadIcon': await MultipartFile.fromFile(path, filename: name)
      });
      await requestNetwork<String>(Method.post, url: "", params: formData, onSuccess: (data) {
        imgPath = data ?? '';
      });
    } catch (e) {
      Toast.show('图片上传失败！');
    }
    return imgPath;
  }

  void _onError(int code, String msg, NetErrorCallback? onError, bool isShowErrorToast) {
    /// 异常时直接关闭加载圈，不受isClose影响
    view.closeProgress();
    if (code != ExceptionHandle.cancel_error&&isShowErrorToast) {
      Toast.show(msg);
    }
    /// 页面如果dispose，则不回调onError
    if (onError != null) {
      onError(code.toString(), msg);
    }
  }
}
